package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.invoke.LambdaMetafactory;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-12
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
//        验证参数
        if(StringUtils.isBlank(dto.getName()) ||
            StringUtils.isBlank(dto.getPassword())){
//            参数不完整
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
//        根据用户名查询用户信息
//        select * from ad_user where name=?
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(queryWrapper);
        if(adUser == null){
//            用户不存在
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
//        验证密码
        String password = adUser.getPassword();
        boolean b = passwordEncoder.matches(dto.getPassword(), password);
//        验证不通过，抛异常返回
        if(!b){
//            密码不正确
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        验证通过，生成token
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 60);
        Map<String, Object> map = new HashMap<>();
        map.put("user", BeanHelper.copyProperties(adUser, AdUserDto.class));
        map.put("token",token);
        return map;
    }
}
